package com.hiof.activities;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.hiof.R;
import com.hiof.antplus.ANTPlusService;
import com.hiof.antplus.AntPlusManager;
import com.hiof.antplus.PairingDialog;
import com.hiof.settings.SettingManager;
import com.hiof.utility.Utility;

public class ANTPlusDemo extends Activity implements View.OnClickListener,
        AntPlusManager.Callbacks {

    /**
     * Button for enabling/disabling ANT
     */
    private ImageButton mAntPlusButton;

    /**
     * Class to manage all the ANT messaging and setup
     */
    private AntPlusManager mAntManager;

    private boolean mBound;

    private PairingDialog mShownDialog = null;

    private final ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // This is very unlikely to happen with a local service (ie. one in
            // the same process)
            mAntManager.setCallbacks(null);
            mAntManager = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mAntManager = ((ANTPlusService.LocalBinder) service).getManager();
            mAntManager.setCallbacks(ANTPlusDemo.this);
            loadConfiguration();
            notifyAntStateChanged();

            if (mShownDialog != null) {
                mShownDialog.setEnabled(true);
                switch (mShownDialog.getId()) {
                    case PairingDialog.HRM_ID:
                        mShownDialog.setDeviceNumber(mAntManager
                                .getDeviceNumberHRM());
                        break;
                    case PairingDialog.BUFF_ID:
                        mShownDialog.setDeviceNumber(mAntManager
                                .getBufferThreshold());
                        break;
                    case PairingDialog.PROX_ID:
                        mShownDialog.setProximityThreshold(mAntManager
                                .getProximityThreshold());
                        break;
                    default:
                        // Other ID's don't matter
                        break;
                }
            }
            init();

        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.antplusmain);
        initControls();
    }

    @Override
    protected void onStart() {
        mBound = bindService(new Intent(this, ANTPlusService.class),
                mConnection, BIND_AUTO_CREATE);
        super.onStart();
    }

    @Override
    protected void onStop() {
        if (mAntManager != null) {
            saveState();
            mAntManager.setCallbacks(null);
        }
        if (mBound) {
            unbindService(mConnection);
        }
        super.onStop();
    }

//    TODO onCreateDialog, OnPairingListener, onPrepareDialog method removed add later if necessary

    /**
     * Store application persistent data.
     */
    private void saveState() {
        SettingManager.getInstance().setAntHRMDeviceNumber(mAntManager.getDeviceNumberHRM());
        SettingManager.getInstance().setProximityThreshold(mAntManager.getProximityThreshold());
        SettingManager.getInstance().setProximityThreshold(mAntManager.getBufferThreshold());
    }

    /**
     * Retrieve application persistent data.
     */
    private void loadConfiguration() {
        // Restore preferences
        mAntManager.setDeviceNumberHRM((short) SettingManager.getInstance().getAntHRMDeviceNumber());
        mAntManager.setProximityThreshold((byte) SettingManager.getInstance().getProximityThreshold());
        mAntManager.setBufferThreshold((short) SettingManager.getInstance().getBufferThreshold());
    }

    /**
     * Initialize GUI elements.
     */
    private void initControls() {
        mAntPlusButton = (ImageButton) findViewById(R.id.button_antplus);
        // Set up button listeners and scaling
        ((ImageButton) findViewById(R.id.button_heart))
                .setOnClickListener(this);
        ((ImageButton) findViewById(R.id.button_heart))
                .setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        ((ImageButton) findViewById(R.id.button_heart))
                .setBackgroundColor(Color.TRANSPARENT);
        mAntPlusButton.setOnClickListener(this);
        mAntPlusButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        mAntPlusButton.setBackgroundColor(Color.TRANSPARENT);
    }

    private void receiveOrUpdateHeartRateInfo(byte channel) {
        if (channel == AntPlusManager.HRM_CHANNEL) {
            switch (mAntManager.getHrmState()) {
                case CLOSED:
                case OFFLINE:
                case SEARCHING:
                case PENDING_OPEN:
                    Utility.debug(this.getClass().getName(), "notifyChannelDataChanged pending--:");
                    break;
                case TRACKING_STATUS:
                    // There is no Status state for the HRM channel, so we will
                    // attempt to show latest data instead
                case TRACKING_DATA:
                    Utility.debug(this.getClass().getName(), "notifyChannelDataChanged value:" + mAntManager.getBPM());
                    break;
            }
        }
    }
    private void init(){
        if (!mAntManager.isChannelOpen(AntPlusManager.HRM_CHANNEL)) {
            if (!mAntManager.isEnabled())
                mAntManager.doEnable();
        }
    }
    public void onClick(View v) {
        if (mAntManager == null)
            return;
        if (v.getId() == R.id.button_antplus) {
            if (mAntManager.isEnabled())
                mAntManager.doDisable();
            else
                mAntManager.doEnable();
            return;
        } else
        if (v.getId() == R.id.button_heart) {
            if (!mAntManager.isChannelOpen(AntPlusManager.HRM_CHANNEL)) {
                Utility.debug(this.getClass().getName(), "onClick (HRM): Open channel");
                mAntManager.openChannel(AntPlusManager.HRM_CHANNEL, false);
            } else {
                Utility.debug(this.getClass().getName(), "onClick (HRM): Close channel");
                mAntManager.closeChannel(AntPlusManager.HRM_CHANNEL);
            }
        }
    }

    // Implementations of the AntPlusManager call backs
    @Override
    public void errorCallback() {
        mAntManager.clearChannelStates();
    }

    @Override
    public void notifyAntStateChanged() {
        boolean showChannels = mAntManager.checkAntState();
        if (!showChannels) {
            mAntManager.clearChannelStates();
        } else {
            receiveOrUpdateHeartRateInfo(AntPlusManager.HRM_CHANNEL);
        }
    }

    @Override
    public void notifyChannelStateChanged(byte channel) {
        receiveOrUpdateHeartRateInfo(channel);
    }

    @Override
    public void notifyChannelDataChanged(byte channel) {
        receiveOrUpdateHeartRateInfo(channel);
    }
}